sizes = [0, 35, 50, 75, 100, 139, 150, 160, 200, 250, 300, 340, 350, 400, 450, 490, 500];

arg = argv;
X = load("-ascii", arg{1})';

[warping, Xw_cow, diagnos] = cow( X(2,:), X(3,:), 30, 6, [1 1 0] );


% coorditanes of the ladder peaks on the original time axis
for i = 1:length(sizes)
  [d, x] = min(abs(X(1,:) - sizes(i)));
  xs(i) = x;
end
xs = [xs, length(X)]; % include the endpoint; 0 is already there (see sizes above)

% apply the warping path in result.txt to the sample and to the
% straight line, T
T = [1:length(X)];
for aN=1:diagnos.Nsegments-1
    tindex = diagnos.indexT(aN):diagnos.indexT(aN)+diagnos.segment_length-1;
    nt = length(tindex);
    pindex = warping(aN):warping(aN+1)-1;
    np = length(pindex);
    p = (0:(nt-1))*(np-1)/(nt-1) + 1;
    xw(tindex) = interp1(1:np,T(pindex),p);
end
tindex = diagnos.indexT(diagnos.Nsegments):length(X(2,:));
nt = length(tindex);
pindex = warping(diagnos.Nsegments):length(X(2,:));
np = length(pindex);
p = (0:(nt-1))*(np-1)/(nt-1) + 1;
xw(tindex) = interp1(1:np,T(pindex),p);

% calculate the warping differential (a difference between the
% straight line (1:length(xw)) and the warping path xw.
df = xw - T;

% The only interesting values of the differential are those
% at the ladder peaks. Interpolate everything in between
time = 1:length(X);
dfi = interp1(xs, df(xs), time);
dfi(end) = dfi(end-1); % get rid of the last Nan
warped_time = time - dfi;

% interpolate sample from warped to straight time
iw_standard = interp1(warped_time, X(3,:), time);
iw_standard(end) = iw_standard(end-1);
iw_sample = interp1(warped_time, X(4,:), time);
iw_sample(end) = iw_sample(end-1);

%plot it all

t = X(1,:);
targ = X(2,:);
stand = X(3,:);
w_standard = Xw_cow(1:length(X));

X = vertcat(X, w_standard, iw_standard, iw_sample, df, dfi)';

save("-ascii", sprintf("%s", arg{2}), "X");
